<?php
namespace App\Http\Controllers\Merchant;
use App\Http\Controllers\BaseController;
use App\Models\AdvInvite;
use App\Models\Merchant;
use App\Models\ProducerAdv;
use Illuminate\Http\Request;

class AdvInviteController extends BaseController
{
    public function index(Request $request) {
        $input['type'] = 'my';
        $title = $input['title'] ?? '';
        $producer_id = $request->input('producer_id');
        $daren_id = $request->input('daren_id');
        $search = ['start_at' => '', 'end_at' => '', 'status' => -1];
        $list = AdvInvite::apply($search, $input)->when($input['type'] == 'my', function ($q) {
            $merchant = $this->getUser();
            if ($merchant->category == Merchant::DAREN)
                $q->where('daren_id', $merchant->id);
            else
                $q->where('producer_id', $merchant->id);
        })->when($title, function ($q) use($title){
            $q->where('title', $title);
        })->when($producer_id, function ($q) use($producer_id){
            $q->where('producer_id', $producer_id);
        })->when($daren_id, function ($q) use($daren_id){
            $q->where('daren_id', $daren_id);
        })->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function store(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'daren_id'  => 'required',
            'adv_id'  => 'required',
        ]);
        $producer = $this->getUser();
        $producer_id = $producer->id;
        $input['producer_id'] = $producer_id;
        $adv_id = $request->input('adv_id');

        $adv = ProducerAdv::find($adv_id);
        if (!$adv)
            return $this->failed('任务不存在');

        $exists = AdvInvite::where('producer_id', $producer_id)
            ->where('daren_id', $input['daren_id'])->where('adv_id', $adv_id)->exists();
        if ($exists)
            return $this->failed('已经邀请过');

        $input['adv_sn'] = $adv->adv_sn;
        $input['title'] = $adv->title;
        $input['fac_title'] = $producer->fac_title;
        $model = AdvInvite::create($input);

        return $this->success(['id' => $model->id], '邀请成功');

    }



}

